package com.cnhaimei.vod.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import android.util.Log;

public class Ftp {
	/** 
	 * 通过ftp上传文件 
	 * @param url ftp服务器地址 如： 192.168.1.110 
	 * @param port 端口如 ： 21 
	 * @param username  登录名 
	 * @param password   密码 
	 * @param remotePath  上到ftp服务器的磁盘路径 
	 * @param fileNamePath  要上传的文件路径 
	 * @param fileName      要上传的文件名 
	 * @return 
	 */ 
	public String url;
	public String port;
	public String username;
	public String password; 
	public String remotePath;
	public String fileNamePath;
	public String fileName;
	
	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getPort() {
		return port;
	}

	public void setPort(String port) {
		this.port = port;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getRemotePath() {
		return remotePath;
	}

	public void setRemotePath(String remotePath) {
		this.remotePath = remotePath;
	}

	public String getFileNamePath() {
		return fileNamePath;
	}

	public void setFileNamePath(String fileNamePath) {
		this.fileNamePath = fileNamePath;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public String ftpUpload() {  
	 FTPClient ftpClient = new FTPClient();  
	 FileInputStream fis = null;  
	 String returnMessage = "0";  
	 try {  
	     ftpClient.connect(url, Integer.parseInt(port));  
	     boolean loginResult = ftpClient.login(username, password);  
	     int returnCode = ftpClient.getReplyCode();  
	     if (loginResult && FTPReply.isPositiveCompletion(returnCode)) {// 如果登录成功  
	         ftpClient.makeDirectory(remotePath);  
	         // 设置上传目录  
	         ftpClient.changeWorkingDirectory(remotePath);  
	         ftpClient.setBufferSize(1024);  
	         ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
	         ftpClient.setControlEncoding("UTF-8");  
	         ftpClient.enterLocalPassiveMode();  
	                 fis = new FileInputStream(fileNamePath + fileName);  
	         ftpClient.storeFile(fileName, fis);  

	         FTPFile[] ftpFiles = ftpClient.listFiles();
	            
	         returnMessage = "1";   //上传成功        
	     } else {// 如果登录失败   
	         returnMessage = "0";  
	         }  
	                
	   
	 } catch (IOException e) {  
	     e.printStackTrace();  
	     throw new RuntimeException("FTP客户端出错！", e);  
	 } finally {  
	     //IOUtils.closeQuietly(fis);  
	 try {  
	     ftpClient.disconnect();  
	 } catch (IOException e) {  
	        e.printStackTrace();  
	        throw new RuntimeException("关闭FTP连接发生异常！", e);  
	    }  
	 }  
	 return returnMessage;  
	}  
	
	public boolean ftpDownload(String url,String port,String username,String password,String remotePath,String fileNamePath,String fileName) {  
		 FTPClient ftpClient = new FTPClient();  
		 FileInputStream fis = null;  
		 boolean bRet = false;  
		 try {  
		     ftpClient.connect(url, Integer.parseInt(port));  
		     ftpClient.setConnectTimeout(2000);//设置2秒超时
		     boolean loginResult = ftpClient.login(username, password);  
		     int returnCode = ftpClient.getReplyCode();  
		     if (loginResult && FTPReply.isPositiveCompletion(returnCode)) {// 如果登录成功  
		         ftpClient.makeDirectory(remotePath);  
		         // 设置上传目录  
		         ftpClient.changeWorkingDirectory(remotePath);  
		         ftpClient.setBufferSize(1024*10);  
		         ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
		         ftpClient.setControlEncoding("UTF-8");  
		         ftpClient.enterLocalPassiveMode();  
		         
		         FTPFile[] ftpFiles = ftpClient.listFiles();
		         int nTotalZipFile = 0;
		         for (int i = 0; i < ftpFiles.length; i++) {
					if (FTPFile.FILE_TYPE == ftpFiles[i].getType()) {
						String strFileName = ftpFiles[i].getName();
						Log.i("FTPFile's name = ", strFileName);
			            // 找到需要下载的文件
			            if (strFileName.equals(fileName)) {
					         
			                System.out.println("download...");
			                // 创建本地目录
			                File file = new File(fileNamePath + fileName);
			                // 下载前时间
			                Date startTime = new Date();

		                    // 下载当个文件
		                    boolean flag = downloadSingle(ftpClient, file, ftpFiles[i]);
		                    
		                    if (flag) {
		                    	bRet = true;   //下载成功        
							}
		                    
			                // 下载完时间
			                Date endTime = new Date();			             
			                break;
			            }
					}
				}
		            
		     } else {// 如果登录失败   
		         bRet = false;
		     }  
		                
		   
		 } catch (Exception e) {  
		     e.printStackTrace();  
		     //throw new RuntimeException("FTP客户端出错！", e);  
		 } finally {  
		     //IOUtils.closeQuietly(fis);  
			 try {  
			     ftpClient.disconnect();  
			 } catch (IOException e) {  
		        e.printStackTrace();  
		        //throw new RuntimeException("关闭FTP连接发生异常！", e);  
		    }  
		 }  
		 return bRet;  
	}  

    /**
     * 下载单个文件.
     * @param localFile 本地目录
     * @param ftpFile FTP目录
     * @return true下载成功, false下载失败
     * @throws IOException 
     */
    private boolean downloadSingle(FTPClient ftpClient, File localFile, FTPFile ftpFile) throws IOException {
        boolean flag = true;
        // 创建输出流
        OutputStream outputStream = new FileOutputStream(localFile);
        // 统计流量
        //response += ftpFile.getSize();
        // 下载单个文件
        flag = ftpClient.retrieveFile(localFile.getName(), outputStream);
        // 关闭文件流
        outputStream.close();
        return flag;
    }

    /**
     * 下载多个文件.
     * @param localFile 本地目录
     * @return true下载成功, false下载失败
     * @throws IOException 
     */
//    private boolean downloadMany(FTPClient ftpClient, File localFile) throws IOException {
//        boolean flag = true;
//        // FTP当前目录
//        if (!currentPath.equals(REMOTE_PATH)) {
//            currentPath = currentPath + REMOTE_PATH + localFile.getName();
//        } else {
//            currentPath = currentPath + localFile.getName();
//        }
//        // 创建本地文件夹
//        localFile.mkdir();
//        // 更改FTP当前目录
//        ftpClient.changeWorkingDirectory(currentPath);
//        // 得到FTP当前目录下所有文件
//        FTPFile[] ftpFiles = ftpClient.listFiles();
//        // 循环遍历
//        for (FTPFile ftpFile : ftpFiles) {
//            // 创建文件
//            File file = new File(localFile.getPath() + "/" + ftpFile.getName());
//            if (ftpFile.isDirectory()) {
//                // 下载多个文件
//                flag = downloadMany(file);
//            } else {
//                // 下载单个文件
//                flag = downloadSingle(file, ftpFile);
//            }
//        }
//        return flag;
//    }
    
	public String ftpUpload(String url,String port,String username,String password,String remotePath,String fileNamePath,String fileName) {  
		 FTPClient ftpClient = new FTPClient();  
		 FileInputStream fis = null;  
		 String returnMessage = "0";  
		 try {  
		     ftpClient.connect(url, Integer.parseInt(port));  
		     boolean loginResult = ftpClient.login(username, password);  
		     int returnCode = ftpClient.getReplyCode();  
		     if (loginResult && FTPReply.isPositiveCompletion(returnCode)) {// 如果登录成功  
		         ftpClient.makeDirectory(remotePath);  
		         // 设置上传目录  
		         ftpClient.changeWorkingDirectory(remotePath);  
		         ftpClient.setBufferSize(1024);  
		         ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
		         ftpClient.setControlEncoding("UTF-8");  
		         ftpClient.enterLocalPassiveMode();  
		         fis = new FileInputStream(fileNamePath + fileName);  
		         boolean bRet = ftpClient.storeFile(fileName, fis);  
		         
		         FTPFile[] ftpFiles = ftpClient.listFiles();
		            
		         returnMessage = "1";   //上传成功        
		     } else {// 如果登录失败   
		         returnMessage = "0";  
		         }  
		                
		   
		 } catch (Exception e) {  
		     e.printStackTrace();  
		     throw new RuntimeException("FTP客户端出错！", e);  
		 } finally {  
		     //IOUtils.closeQuietly(fis);  
		 try {  
		     ftpClient.disconnect();  
		 } catch (IOException e) {  
		        e.printStackTrace();  
		        throw new RuntimeException("关闭FTP连接发生异常！", e);  
		    }  
		 }  
		 return returnMessage;  
		}  
}
